package com.形为型模式.解释器模式;

import javax.net.ssl.SSLEngineResult;
import java.util.HashSet;
import java.util.Set;

/**
 * 抽象表达式
 */
interface Expression{
    boolean interpret(String info);
}

/**
 * 终结符表达式
 */
class TerminalExpression implements Expression{
    private Set<String> set = new HashSet<>();
    TerminalExpression(String[] data){
        for(int i = 0;i<data.length;i++){
            set.add(data[i]);
        }
    }
    @Override
    public boolean interpret(String info) {
        if(set.contains(info)){
            return true;
        }
        return false;
    }
}
/**
 * 非终结符表达式
 */
class AndExpression implements Expression{
   private Expression city = null;
   private Expression person = null;
    AndExpression(Expression city,Expression person){
        this.city = city;
        this.person = person;

    }
    @Override
    public boolean interpret(String info) {
        String s[] = info.split("的");
        return city.interpret(s[0]) && person.interpret(s[1]);
    }
}
/**
 * 环境类
 */
class Context{
   private String[] citys = {"韶关","广州"};
   private String[] persons = {"老人","妇女","儿童"};
   private Expression cityPerson;
    Context(){
        Expression city = new TerminalExpression(citys);
        Expression person = new TerminalExpression(persons);
        cityPerson = new AndExpression(city,person);
    }
    void freeRide(String info){
        boolean ok = cityPerson.interpret(info);
        if(ok){
            System.out.println(String.format("你是:%s 本次乘车免费",info));
        }
        else{
            System.out.println(String.format("%s 你不能免费，车费2元扣除",info));
        }

    }

}
/**
 * 文法规则
 *   <expression> ::= <city>的<person>
 *   <city> ::= 韶关|广州
 *   <person> ::= 老人|妇女|儿童
 *
 * 解释器模式之坐公交
 */
public class InterpreterBus {
    public static void main(String[] args) {
        Context bus=new Context();
        bus.freeRide("韶关的老人");
        bus.freeRide("韶关的年轻人");
        bus.freeRide("广州的妇女");
        bus.freeRide("广州的儿童");
        bus.freeRide("山东的儿童");
    }
}

